/**
 * Copyright (C), 2015-2019, bogewang
 * FileName: ProductSearchServiceImpl
 * Author:   foren236598164@aliyun.com
 * Date:     2019/10/15 14:53
 * Description: ProductSearchServiceImpl
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bogewang.product.service.impl;

import com.bogewang.core.base.BaseApiService;
import com.bogewang.core.base.BaseResponse;
import com.bogewang.product.entity.ProductDTO;
import com.bogewang.product.es.entity.ProductEntity;
import com.bogewang.product.es.repository.ProductRepository;
import com.bogewang.product.service.ProductSearchService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 〈ProductSearchServiceImpl〉
 *
 * @author foren236598164@aliyun.com
 * @create 2019/10/15
 * @since 1.0.0
 */
@RestController
public class ProductSearchServiceImpl extends BaseApiService<List<ProductDTO>> implements ProductSearchService {
    @Autowired
    private ProductRepository productRepository;

    @Override
    public BaseResponse<List<ProductDTO>> search(String name) {
        // 1.拼接查询条件
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        // 2.模糊查询name字段
        builder.must(QueryBuilders.fuzzyQuery("name", name));
        Pageable pageable = new QPageRequest(0, 5);
        // 3.调用ES接口查询
        Page<ProductEntity> page = productRepository.search(builder, pageable);
        // 4.获取集合数据
        List<ProductEntity> content = page.getContent();
        // 5.将entity转换dto
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<ProductDTO> mapAsList = mapperFactory.getMapperFacade().mapAsList(content, ProductDTO.class);
        return setResultSuccess(mapAsList);
    }
}